// 分页组件
<template>
  <div class="pager">
    <a
      href=""
      class="pager-item"
      @click.prevent="handelPage(1)"
      :class="{
        disabled: page == 1,
      }"
      >首页
    </a>
    <a
      href=""
      class="pager-item"
      @click.prevent="handelPage(page - 1)"
      :class="{
        disabled: page == 1,
      }"
      >上一页
    </a>

    <!-- 可选页码 -->
    <a
      href=""
      class="pager-item"
      v-for="item in panelPage"
      :key="item"
      @click.prevent="handelPage(item)"
      :class="{
        active:page == item
        }"
      >{{ item }}
    </a>

    <a
      href=""
      class="pager-item"
      @click.prevent="handelPage(page + 1)"
      :class="{
        disabled: page == pageNumber,
      }"
      >下一页
    </a>

    <a
      href=""
      class="pager-item"
      @click.prevent="handelPage(pageNumber)"
      :class="{
        disabled: page == pageNumber,
      }"
      >尾页
    </a>
    <span class="pager-text">
      <i>{{ page }}</i>
      /
      <i>{{ pageNumber }}</i>
    </span>
  </div>
</template>

<script>
export default {
  // 分页数据不能写死，需要传过来
  props: {
    // 当前页码
    page: {
      type: Number,
      default: 1,
    },
    // 每页限制条数
    limit: {
      type: Number,
      default: 10,
    },
    // 总条数
    total: {
      type: Number,
      default: 0,
    },
    // 中间可选页码
    panelNumber: {
      type: Number,
      default: 10,
    },
  },
  methods: {
    handelPage(newPage) {
      // 不能直接修改父组件props属性的值，因此需要在父组件里注册事件，然后在子组件设置方法修改在传值过来
      // this.page = newPage // Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "page"

      // 页码正确范围
      if (newPage < 1) {
        newPage = 1;
      }
      if (newPage > this.pageNumber) {
        newPage = this.pageNumber;
      }

      // 注册事件
      this.$emit("changePage", newPage);
    },
  },
  computed: {
    // 页码数量
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    // 可选页码：最小页码、最大页码
    minPage() {
      let p = this.page - this.panelNumber / 2;
      if (p < 1) {
        p = 1;
      }
      return p;
    },
    maxPage() {
      let p = this.minPage + this.panelNumber - 1;
      if (p > this.pageNumber) {
        p = this.pageNumber;
      }
      return p;
    },
    panelPage() {
      let pages = [];
      for (let index = this.minPage; index <= this.maxPage; index++) {
        pages.push(index);
      }
      return pages;
    },
  },
};
</script>

<style scoped>
.pager {
  text-align: center;
  margin: 20px 0;
}

.pager .pager-item {
  display: inline-block;
  padding: 5px 7px;
  border: 1px solid #ccc;
  margin: 8px;
  cursor: pointer;
  color: rgb(96, 96, 224);
}

.pager .pager-item.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.pager .pager-item.active {
  color: #f40;
  border: none;
  cursor: auto;
}
</style>
